'use client';

import { useEffect, useMemo, useState } from 'react';
import ImportExportToolbar from './ImportExportToolbar';
import { downloadCsv, downloadXls, downloadXlsx, parseCsv, parseExcelXml, parseXlsx } from '@/lib/importExportUtils';

interface RecordItem {
  id: string;
  userId: string;
  username: string;
  categoryId: string;
  categoryPath: string;
  score: number;
  timeSpent: number;
  points: number;
  createdAt: string;
}

export default function RecordList() {
  const [records, setRecords] = useState<RecordItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [query, setQuery] = useState('');
  const [categoryQuery, setCategoryQuery] = useState('');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [isImporting, setIsImporting] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);

  useEffect(() => {
    fetchRecords();
  }, []);

  const fetchRecords = async () => {
    try {
      setLoading(true);
      const res = await fetch('/api/records');
      const data = await res.json();
      if (data.success) {
        setRecords(data.records);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    const cq = categoryQuery.trim().toLowerCase();
    return records.filter(r => {
      const byUser = !q || r.username.toLowerCase().includes(q);
      const byCat = !cq || r.categoryPath.toLowerCase().includes(cq);
      return byUser && byCat;
    });
  }, [records, query, categoryQuery]);

  const paginatedRecords = filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize);
  const totalPages = Math.ceil(filtered.length / pageSize);

  useEffect(() => {
    // 当过滤结果变化时，重置到第一页
    setCurrentPage(1);
  }, [filtered]);

  const toggleSelectAll = (checked: boolean) => {
    if (checked) {
      const pageIds = new Set(paginatedRecords.map(r => r.id));
      setSelectedIds(prev => {
        const next = new Set(prev);
        pageIds.forEach(id => next.add(id));
        return next;
      });
    } else {
      const pageIds = new Set(paginatedRecords.map(r => r.id));
      setSelectedIds(prev => {
        const next = new Set(prev);
        pageIds.forEach(id => next.delete(id));
        return next;
      });
    }
  };

  const toggleSelectOne = (id: string, checked: boolean) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (checked) next.add(id); else next.delete(id);
      return next;
    });
  };

  const deleteOne = async (id: string) => {
    if (!confirm('确认要删除该记录吗？此操作不可恢复。')) return;
    try {
      const res = await fetch(`/api/records?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
      const data = await res.json();
      if (data.success) {
        await fetchRecords();
        setSelectedIds(prev => {
          const next = new Set(prev);
          next.delete(id);
          return next;
        });
      } else {
        alert(data.message || '删除失败');
      }
    } catch (e) {
      alert('删除失败');
    }
  };

  const deleteSelected = async () => {
    if (selectedIds.size === 0) return;
    if (!confirm(`确认要删除选中的 ${selectedIds.size} 条记录吗？此操作不可恢复。`)) return;
    try {
      const res = await fetch('/api/records', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: Array.from(selectedIds) }),
      });
      const data = await res.json();
      if (data.success) {
        await fetchRecords();
        setSelectedIds(new Set());
      } else {
        alert(data.message || '删除失败');
      }
    } catch (e) {
      alert('删除失败');
    }
  };

  const handleExportSelected = (format: 'csv' | 'xls' | 'xlsx') => {
    const selected = filtered.filter(r => selectedIds.has(r.id));
    if (selected.length === 0) return;
    const headers = ['ID', '时间', '用户名', '分类', '得分', '耗时(秒)', '积分'];
    const rows = selected.map(r => [r.id, new Date(r.createdAt).toLocaleString(), r.username, r.categoryPath, r.score, r.timeSpent, r.points]);
    const filename = `records_selected_${Date.now()}`;
    if (format === 'csv') {
      downloadCsv(`${filename}.csv`, headers, rows);
    } else if (format === 'xls') {
      downloadXls(`${filename}.xls`, headers, rows);
    } else {
      downloadXlsx(`${filename}.xlsx`, headers, rows);
    }
  };

  const handleExportAll = (format: 'csv' | 'xls' | 'xlsx') => {
    if (filtered.length === 0) return;
    const headers = ['ID', '时间', '用户名', '分类', '得分', '耗时(秒)', '积分'];
    const rows = filtered.map(r => [r.id, new Date(r.createdAt).toLocaleString(), r.username, r.categoryPath, r.score, r.timeSpent, r.points]);
    const filename = `records_all_${Date.now()}`;
    if (format === 'csv') {
      downloadCsv(`${filename}.csv`, headers, rows);
    } else if (format === 'xls') {
      downloadXls(`${filename}.xls`, headers, rows);
    } else {
      downloadXlsx(`${filename}.xlsx`, headers, rows);
    }
  };

  const handleDownloadTemplate = (format: 'csv' | 'xls' | 'xlsx') => {
    const headers = ['用户名', '分类路径', '得分', '耗时(秒)', '积分', '时间'];
    const example = ['demo_user', 'Fruit', '8', '120', '680', '2024-01-01 12:00:00'];
    if (format === 'csv') {
      downloadCsv('records_template.csv', headers, [example]);
    } else if (format === 'xls') {
      downloadXls('records_template.xls', headers, [example]);
    } else {
      downloadXlsx('records_template.xlsx', headers, [example]);
    }
  };

  const normalizeHeaderKey = (raw: string): string => {
    const trimmed = (raw || '').trim();
    const lower = trimmed.toLowerCase();
    // 支持中文和英文列名
    const map: Record<string, string> = {
      username: 'username', '用户名': 'username', '用户': 'username',
      categorypath: 'categorypath', '分类路径': 'categorypath', '分类': 'categorypath', 'category': 'categorypath',
      score: 'score', '得分': 'score',
      timespent: 'timespent', '耗时(秒)': 'timespent', '耗时': 'timespent', 'timespent(秒)': 'timespent',
      points: 'points', '积分': 'points',
      createdat: 'createdat', '时间': 'createdat', '创建时间': 'createdat', 'createdat': 'createdat',
    };
    return map[trimmed] ?? map[lower] ?? lower;
  };

  const handleImport = async (file: File, format: 'csv' | 'xls' | 'xlsx') => {
    setIsImporting(true);
    try {
      let rows: string[][];
      if (format === 'csv') {
        const text = await file.text();
        rows = parseCsv(text);
      } else if (format === 'xls') {
        const text = await file.text();
        rows = parseExcelXml(text);
      } else {
        rows = await parseXlsx(file);
      }
      if (rows.length === 0) {
        alert(format === 'xls' ? 'Excel 为空或格式不受支持（请使用.xls XML工作簿或改用CSV）' : '文件为空');
        return;
      }
      const [h0, ...data] = rows;
      const header = h0.map(h => normalizeHeaderKey(String(h)));
      const idxUsername = header.indexOf('username');
      const idxCategoryPath = header.indexOf('categorypath');
      const idxScore = header.indexOf('score');
      const idxTimeSpent = header.indexOf('timespent');
      const idxPoints = header.indexOf('points');
      const idxCreatedAt = header.indexOf('createdat');
      
      if (idxUsername < 0 || idxCategoryPath < 0 || idxScore < 0 || idxTimeSpent < 0) {
        alert('缺少必要列：用户名(或username), 分类路径(或categoryPath), 得分(或score), 耗时(秒)(或timeSpent)');
        return;
      }
      
      let ok = 0, failed = 0;
      const errors: string[] = [];
      for (let i = 0; i < data.length; i++) {
        const r = data[i];
        const username = String(r[idxUsername] || '').trim();
        const categoryPath = String(r[idxCategoryPath] || '').trim();
        const scoreStr = String(r[idxScore] || '').trim();
        const timeSpentStr = String(r[idxTimeSpent] || '').trim();
        const pointsStr = idxPoints >= 0 ? String(r[idxPoints] || '').trim() : '';
        const createdAtStr = idxCreatedAt >= 0 ? String(r[idxCreatedAt] || '').trim() : '';
        
        if (!username || !categoryPath || !scoreStr || !timeSpentStr) {
          failed++;
          errors.push(`第${i + 2}行：用户名、分类路径、得分、耗时不能为空`);
          continue;
        }
        
        const score = parseInt(scoreStr, 10);
        const timeSpent = parseInt(timeSpentStr, 10);
        if (isNaN(score) || isNaN(timeSpent) || score < 0 || timeSpent < 0) {
          failed++;
          errors.push(`第${i + 2}行：得分和耗时必须是有效的非负整数`);
          continue;
        }
        
        const points = pointsStr ? parseInt(pointsStr, 10) : (score * 100 - timeSpent);
        const createdAt = createdAtStr ? new Date(createdAtStr).toISOString() : new Date().toISOString();
        
        try {
          const res = await fetch('/api/records', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              username,
              categoryPath,
              score,
              timeSpent,
              points: isNaN(points) ? (score * 100 - timeSpent) : points,
              createdAt,
            })
          });
          const dataJson = await res.json();
          if (dataJson.success) {
            ok++;
          } else {
            failed++;
            errors.push(`第${i + 2}行：${dataJson.message || '创建失败'}`);
          }
        } catch {
          failed++;
          errors.push(`第${i + 2}行：网络错误`);
        }
      }
      await fetchRecords();
      alert(`导入完成：成功 ${ok} 条，失败 ${failed} 条${errors.length > 0 ? '\n\n前5个错误：\n' + errors.slice(0, 5).join('\n') : ''}`);
    } catch (e) {
      if (e instanceof Error && e.message.includes('xlsx')) {
        alert('请先安装 xlsx 库: npm install xlsx');
      } else {
        alert(`导入失败：${e instanceof Error ? e.message : '未知错误'}`);
      }
    } finally {
      setIsImporting(false);
    }
  };

  if (loading) {
    return (
      <div className="card">
        <div>加载中...</div>
      </div>
    );
  }

  return (
    <div className="card">
      <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', marginBottom: '12px', alignItems: 'center' }}>
        <input
          placeholder="按用户名搜索"
          value={query}
          onChange={e => setQuery(e.target.value)}
          style={{ padding: '8px 10px', border: '1px solid #ddd', borderRadius: 6 }}
        />
        <input
          placeholder="按分类路径搜索"
          value={categoryQuery}
          onChange={e => setCategoryQuery(e.target.value)}
          style={{ padding: '8px 10px', border: '1px solid #ddd', borderRadius: 6 }}
        />
        <button className="btn btn-secondary" onClick={fetchRecords} style={{ padding: '6px 8px', fontSize: '12px' }}>刷新</button>
        <button
          className="btn btn-danger"
          onClick={deleteSelected}
          disabled={selectedIds.size === 0}
          title={selectedIds.size === 0 ? '请选择记录后再删除' : ''}
          style={{ padding: '6px 8px', fontSize: '12px' }}
        >
          删除选中
        </button>
        <ImportExportToolbar
          onExportSelected={handleExportSelected}
          onExportAll={handleExportAll}
          onImport={handleImport}
          onDownloadTemplate={handleDownloadTemplate}
          isImporting={isImporting}
          selectedCount={selectedIds.size}
          totalCount={filtered.length}
        />
      </div>

      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ backgroundColor: '#f5f5f5' }}>
              <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>
                <input
                  type="checkbox"
                  checked={paginatedRecords.length > 0 && paginatedRecords.every(r => selectedIds.has(r.id))}
                  onChange={e => toggleSelectAll(e.target.checked)}
                />
              </th>
              <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>时间</th>
              <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>用户名</th>
              <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>分类</th>
              <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>得分</th>
              <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>耗时(秒)</th>
              <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>积分</th>
              <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>操作</th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 ? (
              <tr>
                <td colSpan={8} style={{ padding: '16px', textAlign: 'center' }}>暂无记录</td>
              </tr>
            ) : (
              paginatedRecords.map(r => (
                <tr key={r.id} style={{ borderBottom: '1px solid #eee' }}>
                  <td style={{ padding: '10px' }}>
                    <input
                      type="checkbox"
                      checked={selectedIds.has(r.id)}
                      onChange={e => toggleSelectOne(r.id, e.target.checked)}
                    />
                  </td>
                  <td style={{ padding: '10px', whiteSpace: 'nowrap' }}>{new Date(r.createdAt).toLocaleString()}</td>
                  <td style={{ padding: '10px' }}>{r.username}</td>
                  <td style={{ padding: '10px' }}>{r.categoryPath}</td>
                  <td style={{ padding: '10px' }}>{r.score}</td>
                  <td style={{ padding: '10px' }}>{r.timeSpent}</td>
                  <td style={{ padding: '10px' }}>{r.points}</td>
                  <td style={{ padding: '10px' }}>
                    <button className="btn btn-danger" onClick={() => deleteOne(r.id)} style={{ padding: '6px 8px', fontSize: '12px' }}>删除</button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
      {filtered.length > 0 && (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '15px', borderTop: '1px solid #eee' }}>
          <div>
            共 {filtered.length} 条，第 {currentPage} / {totalPages} 页
          </div>
          <div style={{ display: 'flex', gap: '8px' }}>
            <button className="btn" onClick={() => setCurrentPage(1)} disabled={currentPage === 1}>首页</button>
            <button className="btn" onClick={() => setCurrentPage(p => Math.max(1, p - 1))} disabled={currentPage === 1}>上一页</button>
            <button className="btn" onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))} disabled={currentPage === totalPages}>下一页</button>
            <button className="btn" onClick={() => setCurrentPage(totalPages)} disabled={currentPage === totalPages}>末页</button>
          </div>
        </div>
      )}

      {isImporting && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            backgroundColor: 'rgba(255, 255, 255, 0.7)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: 2000,
            pointerEvents: 'auto',
            cursor: 'wait',
          }}
        >
          <div style={{ padding: '24px 32px', backgroundColor: '#fff', borderRadius: '8px', boxShadow: '0 4px 12px rgba(0,0,0,0.15)', fontSize: '16px', color: '#333' }}>
            正在导入文件，请稍候...
          </div>
        </div>
      )}
    </div>
  );
}


